package com.user.basic.analyze.sex;

import com.entity.analyze.Sex;
import com.user.basic.analyze.BaseAnalyzeService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class SexAnalyzeServiceImpl extends BaseAnalyzeService<SexAnalyzeEntity> implements SexAnalyzeService {
    private final SexAnalyzeMapper sexAnalyzeMapper;
    public SexAnalyzeServiceImpl(SexAnalyzeMapper sexAnalyzeMapper){
        this.sexAnalyzeMapper = sexAnalyzeMapper;
    }
    @Override
    public void group() {
        List<SexAnalyzeEntity> sexAnalyzeEntities = sexAnalyzeMapper.groupBySex();
        save(sexAnalyzeEntities);
    }

    @Override
    public void save(List<SexAnalyzeEntity> sexAnalyzeEntity) {
        AtomicInteger sum = new AtomicInteger(0);
        AtomicInteger illSex = new AtomicInteger(0);
        List<Sex> sexes = new ArrayList<>();
       sexAnalyzeEntity.stream().forEach(sexAnalyzeEntity1 -> {
           if (sexAnalyzeEntity1.getName() != null){
               Sex sex = new Sex();
               sex.setName(sexAnalyzeEntity1.getName());
               sex.setTotal(sexAnalyzeEntity1.getCount());
               sex.setId(UUID.randomUUID().toString());
               sex.setCreateTime(new Date());
               sexes.add(sex);
           }
           sum.getAndAdd(sexAnalyzeEntity1.getCount());
           if (!sexAnalyzeEntity1.getName().equals("1")
                   && !sexAnalyzeEntity1.getName().equals("2")
                   && !sexAnalyzeEntity1.getName().equals("3")){
               illSex.getAndAdd(sexAnalyzeEntity1.getCount());
           }
       });
        for (Sex sex : sexes) {
            if (sex.getName().equals("3")){
                sex.setName("未知");
                sex.setTotal(sex.getTotal()+illSex.get());
            }else if (sex.getName().equals("1")){
                sex.setName("男");
            }else if (sex.getName().equals("2")){
                sex.setName("女");
            }
            sex.setPercent(Float.parseFloat(String.format("%.2f",
                    (((float)sex.getTotal())/((float)sum.get()) *100))));

            sexAnalyzeMapper.save(sex);
        }
    }

}
